package com.hingstd.lastwork.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled " + "FROM user_accounts WHERE username =?")
                .authoritiesByUsernameQuery("SELECT username, role " + "FROM user_accounts WHERE username = ?")
                .passwordEncoder(bCryptPasswordEncoder);

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/articles/new").hasRole("ADMIN")
                .antMatchers("/articles/save").hasRole("ADMIN")
                .antMatchers("/warns/new").hasRole("ADMIN")
                .antMatchers("/warns/save").hasRole("ADMIN")
                .antMatchers("/attendances/new").hasRole("ADMIN")
                .antMatchers("/attendances/save").hasRole("ADMIN")

                .antMatchers("/","/**").permitAll()//有先后顺序不能在前面
                .and()
                .formLogin();
//                .antMatchers("/h2-console/**").permitAll()
//                .antMatchers("/").authenticated().and().formLogin();
//
//        http.csrf().disable();
//        http.headers().frameOptions().disable();

    }
}

